import logging
import threading

from sqlalchemy_tool.config import SessionLocal
from typing import Callable


class Transcation:
    """事务管理注解"""

    def __init__(self):
        self.local = threading.local()
        self.local.session = None

    def __call__(self, func):
        def func_wrapper(*args, **kwargs):
            with SessionLocal() as session:
                try:
                    self.local.session = session
                    if isinstance(func, Callable):
                        flag = func(*args, **kwargs)
                    else:
                        flag = func.__func__(*args, **kwargs)
                except Exception as ex:
                    logging.error('数据库操作出现异常，操作方法是:%s， 异常是：%s' % (func.__name__, str(ex)))
                    session.rollback()
                    return False
                else:
                    session.commit()
                    return flag
        return func_wrapper

    def get_session(self):
        if self.local.session:
            return self.local.session
        else:
            return SessionLocal()
